package com.study.talk.ui.app.chat

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.Menu
import android.view.View
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.study.talk.R
import com.study.talk.ui.app.base.BaseActivity
import com.study.talk.databinding.ActivityChatBinding
import com.study.talk.netty.NettyClient
import com.study.talk.netty.message.request.MessageRequest
import com.study.common.DateUtil
import com.study.talk.data.model.MessageRecord
import com.study.talk.utils.FileUtil
import com.study.talk.ui.adapter.chat.ChatMsgAdapter
import com.study.talk.data.model.UserInfo
import com.study.talk.ui.app.common.AnalyzeImageFragment
import com.study.talk.ui.app.common.SmartChatFragment
import com.study.talk.utils.extras.getIntParam
import com.study.talk.utils.extras.imageUrl
import com.study.talk.utils.extras.showToast
import com.study.talk.utils.extras.take
import com.study.talk.utils.extras.toUserDetails
import com.study.talk.utils.extras.useless
import com.volcengine.ark.runtime.model.completion.chat.ChatCompletionContentPart
import com.volcengine.ark.runtime.model.completion.chat.ChatMessage
import com.volcengine.ark.runtime.model.completion.chat.ChatMessageRole
import dagger.hilt.android.AndroidEntryPoint


@AndroidEntryPoint
class ChatActivity : BaseActivity(), View.OnClickListener {

    companion object {
        private const val TAG = "ChatActivity"
        const val DATA_NAME = "userId"
    }

    private val vm: ChatViewModel by viewModels()

    private val adapter: ChatMsgAdapter by lazy { ChatMsgAdapter(vm) }

    private val selectPhoto =
        registerForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri: Uri? ->
            uri?.let { vm.sendImage(FileUtil.getPathFromUri(this, it)) }
        }
    private val takePhoto =
        registerForActivityResult(ActivityResultContracts.TakePicture()) { result: Boolean ->
            if (result) {
                uri?.let { vm.sendImage(FileUtil.getPathFromUri(this, it)) }
            }
        }

    private val binding: ActivityChatBinding by lazy { ActivityChatBinding.inflate(layoutInflater) }

    private val friendId by lazy { getIntParam(DATA_NAME) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        setSupportActionBar(binding.chatToolbar)
        binding.chatListView.layoutManager = LinearLayoutManager(this)
        binding.chatListView.adapter = adapter
        vm.friend.observe(this) {
            initView(it)
        }
        vm.selectModel.observe(this) {
            if (it) {
                binding.chatBottomOption.visibility = View.GONE
                binding.chatBottomOptionSelect.visibility = View.VISIBLE
                adapter.selectModel()
            } else {
                binding.chatBottomOptionSelect.visibility = View.GONE
                binding.chatBottomOption.visibility = View.VISIBLE
                adapter.normalModel()
            }
        }
        vm.analyzeContent.observe(this) {
            analyzeChatContent(it)
        }
        vm.loadFriendInfo(friendId)
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.chat_menu, menu)
        return super.onCreateOptionsMenu(menu)
    }

    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        vm.loadFriendInfo(intent.getIntExtra(DATA_NAME, -1))
    }

    private fun initView(user: UserInfo) {

        vm.loadMsg(user.id).observe(this@ChatActivity) { msg ->
            adapter.submitList(msg)
            if (msg.isNotEmpty()) {
                binding.chatListView.post {
                    binding.chatListView.smoothScrollToPosition(msg.size - 1)
                }
            }
        }

        supportActionBar?.title = "与好友${user.nickName}聊天"
        binding.chatToolbar.setNavigationOnClickListener { finish() }
        binding.chatToolbar.setOnMenuItemClickListener { item ->
            when (item.itemId) {
                R.id.chat_menu_user_info -> {
                    toUserDetails(user.id)
                }

                R.id.chat_other_setting -> showToast("功能开发中...")
                else -> finish()
            }
            true
        }

        binding.chatMsgSendBt.setOnClickListener { _ ->
            if (binding.chatMsgEdit.useless("不能发送空消息或者空格内容哦")) return@setOnClickListener
            val contentText = binding.chatMsgEdit.take()
            val messageRequest = MessageRequest().apply {
                receiverId = user.id
                content = contentText
                messageType = 0
                dateTime = DateUtil.currentTime()
            }
            NettyClient.sendMessage(messageRequest)
        }

        binding.chatBottomMenuAudio.setOnClickListener(this)
        binding.chatBottomMenuEmoji.setOnClickListener(this)
        binding.chatBottomMenuOther.setOnClickListener(this)

        binding.chatBottomMenuImage.setOnClickListener {
            showSelectPhotoDialog(selectPhoto, takePhoto)
        }

        binding.chatBottomOptionSelectCancel.setOnClickListener {
            adapter.clearSelected()
            vm.changeSelectModel(false)
        }

        binding.chatBottomOptionSelectSmartAnalyze.setOnClickListener {
            val msgList = adapter.getSelectMsg()
            if (msgList.isNotEmpty()) {
                if (msgList.any { it.messageType == 1 }) {
                    val fragment = AnalyzeImageFragment(buildContexts(msgList))
                    fragment.show(supportFragmentManager, "chatFragment")
                } else {
                    val fragment = SmartChatFragment(buildContent(msgList))
                    fragment.show(supportFragmentManager, "chatFragment")
                }
            } else {
                showToast("您未选择任何消息")
            }
        }
    }

    override fun onClick(v: View) {
        showToast("功能开发中...")
    }

    /** 没有图片的情况 */
    private fun buildContent(msgList: List<MessageRecord>): String {
        return buildString {
            append("下面的内容是我和好友").append(vm.friend.value?.nickName).append("的对话")
                .append("\n")
            msgList.forEach {
                if (it.self) {
                    append("我:").append(it.content).append("\n")
                } else {
                    append("好友:").append(it.content).append("\n")
                }
            }
            append("请帮忙分析这段对话的内容")
        }
    }

    /** 有图片的情况 */
    private fun buildContexts(msgList: List<MessageRecord>): MutableList<ChatMessage> {
        val contexts = mutableListOf<ChatCompletionContentPart>(
            ChatCompletionContentPart.builder().type("text")
                .text("下面的内容是我和好友${vm.friend.value?.nickName}的对话").build()
        )
        msgList.forEach {
            val role = if (it.self) "我" else "好友"
            if (it.messageType == 0) {
                contexts.add(
                    ChatCompletionContentPart.builder().type("text").text("${role}:${it.content}")
                        .build()
                )
            } else {
                contexts.add(
                    ChatCompletionContentPart.builder().type("text").text("${role}发送了图片")
                        .build()
                )
                contexts.add(
                    ChatCompletionContentPart.builder().type("image_url")
                        .imageUrl(ChatCompletionContentPart.ChatCompletionContentPartImageURL(it.content.imageUrl()))
                        .build()
                )
            }
        }
        contexts.add(
            ChatCompletionContentPart.builder().type("text").text("请帮忙分析这段对话").build()
        )
        return mutableListOf(
            ChatMessage.builder().multiContent(contexts.toList()).role(ChatMessageRole.USER).build()
        )
    }
}